package org.example;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

/**
 * Java程序获取java命令的绝对路径和目录
 */
public class javaCommandPath {
    public static void main(String[] args) {
        try {
            //linux用 which java 命令,windows用 where java 命令
            String osName = System.getProperty("os.name");
            String cmd = "";
            if (osName.toLowerCase().contains("windows")) {
                cmd = "where java";
            } else if (osName.toLowerCase().contains("linux")) {
                cmd = "which java";
            } else {
                throw new RuntimeException("Unsupported OS: " + osName);
            }

            System.out.println("File.separator is "+File.separator);


            Process process = Runtime.getRuntime().exec(cmd);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String javaPath = reader.readLine();
            process.waitFor();

            System.out.println("Java command absolute path: " + javaPath);
            if (javaPath != null && javaPath.contains(File.separator)) {
                String javaDir = javaPath.substring(0, javaPath.lastIndexOf(File.separator));
                System.out.println("Java command directory: " + javaDir);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getJavaPath() {
        try {
            //linux用 which java 命令,windows用 where java 命令
            String osName = System.getProperty("os.name");
            String cmd = "";
            if (osName.toLowerCase().contains("windows")) {
                cmd = "where java";
            } else if (osName.toLowerCase().contains("linux")) {
                cmd = "which java";
            } else {
                throw new RuntimeException("Unsupported OS: " + osName);
            }

            System.out.println("File.separator is " + File.separator);
            Process process = Runtime.getRuntime().exec(cmd);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String javaPath = reader.readLine();
            process.waitFor();

            System.out.println("Java command absolute path: " + javaPath);
            return javaPath;
        } catch (Exception e) {
            System.out.println("发生异常了");
        }

        return "exception";
    }
}
